package com.ruoyi.classroom.course.service.impl;

import com.ruoyi.classroom.course.domain.Course;
import com.ruoyi.classroom.course.domain.CourseManager;
import com.ruoyi.classroom.course.mapper.CourseManagerMapper;
import com.ruoyi.classroom.course.service.ICourseManagerService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;

/**
 * 排课管理Service业务层处理
 * 
 * @author lgm
 * @date 2024-07-19
 */
@Service
public class CourseManagerServiceImpl implements ICourseManagerService
{
    @Autowired
    private CourseManagerMapper courseManagerMapper;

    boolean flag =true;
    /**
     * 查询排课管理
     * 
     * @param id 排课管理主键
     * @return 排课管理
     */
    @Override
    public CourseManager selectCourseManagerById(Long id)
    {
        return courseManagerMapper.selectCourseManagerById(id);
    }

    /**
     * 查询排课管理列表
     * 
     * @param courseManager 排课管理
     * @return 排课管理
     */
    @Override
    public List<CourseManager> selectCourseManagerList(CourseManager courseManager)
    {
        return courseManagerMapper.selectCourseManagerList(courseManager);
    }

    /**
     * 新增排课管理
     * 
     * @param courseManager 排课管理
     * @return 结果
     */
    @Override
    public int insertCourseManager(CourseManager courseManager)
    {
        return courseManagerMapper.insertCourseManager(courseManager);
    }

    /**
     * 修改排课管理
     * 
     * @param courseManager 排课管理
     * @return 结果
     */
    @Override
    public int updateCourseManager(CourseManager courseManager) {
        List<CourseManager> list = courseManagerMapper.selectCourseManagerListNoParams();
        System.out.println(list);
        for (CourseManager manager : list) {
            if ( manager.getCourseweek().equals(courseManager.getCourseweek())
                            && manager.getArrangement().equals(courseManager.getArrangement())
                            && manager.getTerm().equals(courseManager.getTerm())
                            && manager.getYears().equals(courseManager.getYears())
            ) {
                return 0;
            }
        }
        return courseManagerMapper.updateCourseManager(courseManager);
    }


    /**
     * 批量删除排课管理
     * 
     * @param ids 需要删除的排课管理主键
     * @return 结果
     */
    @Override
    public int deleteCourseManagerByIds(Long[] ids)
    {
        return courseManagerMapper.deleteCourseManagerByIds(ids);
    }

    /**
     * 删除排课管理信息
     * 
     * @param id 排课管理主键
     * @return 结果
     */
    @Override
    public int deleteCourseManagerById(Long id)
    {
        return courseManagerMapper.deleteCourseManagerById(id);
    }

    /*@Override
    public List<CourseManager> selectCourseManagerListOne(CourseManager courseManager) {
        List<CourseManager> courses = courseManagerMapper.selectCourseManagerListNoParams();

        Set<String> addedCourses = new HashSet<>();
//        1,根据现在的时间，查询出years的-前为上一年的时间的所有课程；
        int currentYear = LocalDate.now().getYear();
//        拼接一个字符串“(currentYear-1)-currentYear”
        String years = String.valueOf(currentYear-1) + "-" + String.valueOf(currentYear);
        CourseManager manager = new CourseManager();
        manager.setYears(years);
//        获取到上一年的课程
        List<CourseManager> courseManagers = courseManagerMapper.selectCourseManagerList(manager);
        // 先将所有课程添加到result中
        List<CourseManager> result = new ArrayList<>(courseManagers);
        System.out.println(courseManagers);
        // 定义所有可能的课程周和安排选项
        List<String> daysOfWeek = Arrays.asList("星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
        List<String> timeSlots = Arrays.asList("第一节课", "第二节课", "第三节课", "第四节课");
        // 定义每个课程ID需要插入的次数
        Map<Long, Long> insertCounts = new HashMap<>();
        insertCounts.put(16L, 5L);
        insertCounts.put(17L, 4L);
        insertCounts.put(18L, 3L);
        insertCounts.put(19L, 2L);
        insertCounts.put(20L, 1L);
        Random random = new Random();
        int totalInserted = 0;
        int maxCombinations = 20;
        for (Map.Entry<Long, Long> entry : insertCounts.entrySet()) {
            Long courseId = entry.getKey();
            Long timesToInsert = entry.getValue();

            Set<String> usedCombinations = new HashSet<>();
            while (totalInserted < maxCombinations && usedCombinations.size() < timesToInsert) {
                String day = daysOfWeek.get(random.nextInt(daysOfWeek.size()));
                String time = timeSlots.get(random.nextInt(timeSlots.size()));
                String combination = day + "_" + time;
                if (!usedCombinations.contains(combination)) {
                    usedCombinations.add(combination);
                    totalInserted++;
                    // 确保我们没有超出最大组合数
                    if (totalInserted <= maxCombinations) {
                            CourseManager newCourseManager = new CourseManager();
                            newCourseManager.setCourseweek(day);
                            newCourseManager.setArrangement(time);
                            newCourseManager.setName(courseManager1.getName());
                            newCourseManager.setHours(courseManager1.getHours());
//                        credits
                            newCourseManager.setCredits(courseManager1.getCredits());
//                        term，根据获取的当前月份，如果是6月之前就是第一学期，否者就是第二学期
                            newCourseManager.setTerm(LocalDate.now().getMonthValue() < 6 ? "第一学期" : "第二学期");
//                          years
                            newCourseManager.setYears(courseManager1.getYears());
//                        coursedesc
                            newCourseManager.setCoursedesc(courseManager1.getCoursedesc());
//                        classroom
                            newCourseManager.setClassroom(courseManager1.getClassroom());
//                        maxnum
                            newCourseManager.setMaxnum(courseManager1.getMaxnum());
//                        imgs
                            newCourseManager.setImgs(courseManager1.getImgs());
//                        user_id
                            newCourseManager.setUserId(courseManager1.getUserId());
                            courseManagerMapper.insertCourseManager(newCourseManager);

                    }
                }
            }
        }
        return result;
    }
*/

    @Override
    public List<CourseManager> selectCourseManagerListOne(CourseManager courseManager) {
        List<CourseManager> coursesAll = courseManagerMapper.selectCourseManagerListNoParams();
        for (CourseManager manager : coursesAll) {
//                  如果id<=20并且term为第二学期，就把is_used为1
            if (manager.getId() <= 20 && manager.getTerm().equals("第二学期")) {
                manager.setIsUsed(1);
            }
            courseManagerMapper.updateCourseManager(manager);
        }
          if (!flag){
//            定义一个Long[]用于存储后续要删除的id
            Long[] ids = new Long[]{};
//            删除id20为之后的所有数据
            List<CourseManager> courses = courseManagerMapper.selectCourseManagerListNoParams();
            for (CourseManager course : courses) {
                if (course.getId() > 20) {
//                    把course的id添加到ids中
                    ids = ArrayUtils.add(ids, course.getId());
                    courseManagerMapper.deleteCourseManagerByIds(ids);
                }
            }
//            flag取反
              flag = !flag;
        }
        Set<String> addedCourses = new HashSet<>();
//        1,根据现在的时间，查询出years的-前为上一年的时间的所有课程；
        int currentYear = LocalDate.now().getYear();
//        拼接一个字符串“(currentYear-1)-currentYear”
        String years = String.valueOf(currentYear-1) + "-" + String.valueOf(currentYear);
        CourseManager manager = new CourseManager();
        manager.setYears(years);
//        获取到上一年的课程
        List<CourseManager> courseManagers = courseManagerMapper.selectCourseManagerList(manager);
        // 先将所有课程添加到result中
        List<CourseManager> result = new ArrayList<>(courseManagers);
        System.out.println(courseManagers);
        // 定义所有可能的课程周和安排选项
        List<String> daysOfWeek = Arrays.asList("星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
        List<String> timeSlots = Arrays.asList("第一节课", "第二节课", "第三节课", "第四节课");
        // 定义每个课程ID需要插入的次数
        Map<Long, Long> insertCounts = new HashMap<>();
        insertCounts.put(20L, 1L);
        insertCounts.put(19L, 2L);
        insertCounts.put(18L, 3L);
        insertCounts.put(17L, 4L);
        insertCounts.put(16L, 5L);
        Random random = new Random();
        int maxCombinations = 20;

// 创建一个映射，用于快速查找result中特定ID的CourseManager
        Map<Long, CourseManager> courseManagerById = new HashMap<>();
        for (CourseManager cm : result) {
            courseManagerById.put(cm.getId(), cm);
        }

// 创建一个映射，用于存储每个课程ID的已使用组合
        Map<Long, Set<String>> usedCombinationsByCourseId = new HashMap<>();

        for (Map.Entry<Long, Long> entry : insertCounts.entrySet()) {
            Long courseId = entry.getKey();
            Long timesToInsert = entry.getValue();

            // 初始化或获取特定课程ID的已使用组合集
            Set<String> usedCombinations = usedCombinationsByCourseId.computeIfAbsent(courseId, k -> new HashSet<>());

            while (usedCombinations.size() < timesToInsert) {
                String day = daysOfWeek.get(random.nextInt(daysOfWeek.size()));
                String time = timeSlots.get(random.nextInt(timeSlots.size()));
                String combination = day + "_" + time;

                if (!usedCombinations.contains(combination)) {
                    usedCombinations.add(combination);

                    // 如果没有超出最大组合数，创建并插入新的CourseManager实例
                    if (usedCombinations.size() <= maxCombinations) {
                        CourseManager baseCourseManager = courseManagerById.get(courseId);
                        if (baseCourseManager != null) {
                            CourseManager newCourseManager = new CourseManager();
                            newCourseManager.setCourseweek(day);
                            newCourseManager.setArrangement(time);
                            newCourseManager.setName(baseCourseManager.getName());
                            newCourseManager.setHours(baseCourseManager.getHours());
                            newCourseManager.setCredits(baseCourseManager.getCredits());
                            newCourseManager.setTerm(LocalDate.now().getMonthValue() < 6 ? "第一学期" : "第二学期");
                            newCourseManager.setYears(String.valueOf(currentYear) + "-" + String.valueOf(currentYear+1));
                            newCourseManager.setCoursedesc(baseCourseManager.getCoursedesc());
                            newCourseManager.setClassroom(baseCourseManager.getClassroom());
                            newCourseManager.setMaxnum(baseCourseManager.getMaxnum());
                            newCourseManager.setImgs(baseCourseManager.getImgs());
                            newCourseManager.setUserId(baseCourseManager.getUserId());
                            newCourseManager.setIsUsed(0);
                            courseManagerMapper.insertCourseManager(newCourseManager);
                        }
                    }
                }
            }
        }
            flag=!flag;
            List<CourseManager> coursesAllN = courseManagerMapper.selectCourseManagerListNoParams();
        for (CourseManager managers : coursesAllN) {
            if (managers.getId() <= 20 && managers.getTerm().equals("第二学期")) {
                managers.setIsUsed(0);
            }
            courseManagerMapper.updateCourseManager(managers);
        }
        return result;
    }

}
